package com.anosine.gpsl.android.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.base.BaseActivity;
import com.anosine.gpsl.android.presenter.BasePresenterActivity;
import com.anosine.gpsl.android.ui.fragment.CommonHeaderFragment;
import com.anosine.gpsl.android.util.MyExpandableListAdapter;
import com.anosine.gpsl.android.util.ShowConfirmDlgA;
import com.anosine.gpsl.android.widget.CustomExpandableListView;
import com.anosine.gpsl.android.widget.ListViewForScrollView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * @Title: OfflineActivityNew
 * @Package com.anosine.gpsl.android.ui.activity
 * @Description: 
 * @author: sunny
 * @date: 2015-11-24
 * @version V1.0
 */
public class OfflineActivity extends BasePresenterActivity implements MKOfflineMapListener {
	private MKOfflineMap mOffline = null;
	private ImageView btn_left, btn_right;
	private LinearLayout layout_download;
	private RelativeLayout layout_current_city;
	private TextView text_name;
	private ListView localmaplist;
	private ArrayList<MKOLUpdateElement> records0 = null;
	private ArrayList<MKOLSearchRecord> records1;
	private ArrayList<MKOLSearchRecord> records2;
	private LocalMapAdapter localadapter;
	private ScrollView scroll_citylist;
	private ListViewForScrollView hotcitylist;
	private CustomExpandableListView expandable;
	private boolean click = true;
	private boolean[] IsClick=new boolean [1000];
	int length=0;
	private MKOLUpdateElement e;
	private LocationClient mLocationClient;
	private MyLocationListenner myListener;
	TextView title;
	Button back;
	
	public class MyLocationListenner implements BDLocationListener {
		@Override
		// 接收位置信息
		public void onReceiveLocation(final BDLocation location) {
			if (location == null) {
				return;
			} 
			text_name.setText(location.getCity());
			layout_current_city.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mOffline.start(Integer.valueOf(location.getCityCode()));
					switchDownload();
					updateView();
				}
			}); 
			mLocationClient.stop();// 停止定位
		}

		// 接收POI信息函数
		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(this.getApplicationContext());
		setContentView(R.layout.activity_offline_new);

		mOffline = new MKOfflineMap();
		mOffline.init(this);
		initView();
		setListener();
		
		mLocationClient = new LocationClient(this);
		myListener = new MyLocationListenner();
		mLocationClient.registerLocationListener(myListener);
		setLocationOption();// 设定定位参数
		mLocationClient.start();// 开始定位
	}

	private void initView() {

		btn_left = (ImageView) findViewById(R.id.iv_left);
		btn_right = (ImageView) findViewById(R.id.iv_right);

		layout_download = (LinearLayout) findViewById(R.id.layout_download);
		layout_current_city = (RelativeLayout) findViewById(R.id.layout_current_city);
		text_name = (TextView) findViewById(R.id.text_name);
		localmaplist = (ListView) findViewById(R.id.localmaplist); 
		scroll_citylist = (ScrollView) findViewById(R.id.scroll_citylist);
		hotcitylist = (ListViewForScrollView) findViewById(R.id.hotcitylist);
		expandable = (CustomExpandableListView) findViewById(R.id.expandable);
		title=(TextView)findViewById(R.id.content_tv_title);
		title.setText("离线地图下载");
		back=(Button)findViewById(R.id.button_left);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void setListener() {

		btn_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				switchDownload();
			}
		});

		btn_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				switchCityList();
			}
		});

		// 获取已下过的离线地图信息
		records0 = mOffline.getAllUpdateInfo();
		if (records0 == null) {
			records0 = new ArrayList<MKOLUpdateElement>();
		}
		//初始化大小,与值
		length=records0.size();
		for(int i=0;i<records0.size();i++){
			IsClick[i]=true;
		}
		localadapter = new LocalMapAdapter();
		localmaplist.setAdapter(localadapter);

		records1 = mOffline.getHotCityList();
		if (records1 != null) {
			List<Map<String, String>> listitem = new ArrayList<Map<String, String>>();
			for (MKOLSearchRecord r : records1) {
				Map<String, String> title = new HashMap<String, String>();
				title.put("name", r.cityName);
				title.put("size", formatDataSize(r.size));
				listitem.add(title);
			}
			SimpleAdapter adapter = new SimpleAdapter(this, listitem, R.layout.offline_hotcity_item, new String[] {
					"name", "size" }, new int[] { R.id.text_name, R.id.text_size });
			hotcitylist.setAdapter(adapter);
			hotcitylist.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		
					final ShowConfirmDlgA dialog = new ShowConfirmDlgA(
							OfflineActivity.this, "确定要下载此地图离线包吗？","下载提示");
					TextView cancel = dialog.getCancel();
					TextView ok = dialog.getOk();
					ok.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							mOffline.start(records1.get(position).cityID);
							switchDownload();
							updateView();
							dialog.dismiss();
						}
					});
					cancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialog.dismiss();
						}
					});
					dialog.show();
				}
			});
			scroll_citylist.smoothScrollTo(0, 0);
		}

		records2 = mOffline.getOfflineCityList();
		if (records1 != null) {
			MyExpandableListAdapter adapter = new MyExpandableListAdapter(this, records2);
			expandable.setAdapter(adapter);
			expandable.setOnGroupClickListener(new OnGroupClickListener() {

				@Override
				public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
					if (records2.get(groupPosition).childCities == null) {
						final ShowConfirmDlgA dialog = new ShowConfirmDlgA(
								OfflineActivity.this, "确定要下载此地图离线包吗？","下载提示");
						TextView cancel = dialog.getCancel();
						TextView ok = dialog.getOk();
						ok.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								mOffline.start(records2.get(groupPosition).cityID);
								switchDownload();
								updateView();
								dialog.dismiss();
							}
						});
						cancel.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								dialog.dismiss();
							}
						});
						dialog.show();
//						mOffline.start(records2.get(groupPosition).cityID);
//						switchDownload();
//						updateView();
						return true;
					} else {
						return false;
					} 
				}
			});
			expandable.setOnChildClickListener(new OnChildClickListener() {

				@Override
				public boolean onChildClick(ExpandableListView parent, View v, final int groupPosition, final int childPosition,
						long id) {
					final ShowConfirmDlgA dialog = new ShowConfirmDlgA(
							OfflineActivity.this, "确定要下载此地图离线包吗？","下载提示");
					TextView cancel = dialog.getCancel();
					TextView ok = dialog.getOk();
					ok.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							mOffline.start(records2.get(groupPosition).childCities.get(childPosition).cityID);
							switchDownload();
							updateView();
							dialog.dismiss();
						}
					});
					cancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialog.dismiss();
						}
					});
					dialog.show();
					return true;
				}
			});
		}
	}
	
	// 设置相关参数
		private void setLocationOption() {
			LocationClientOption option = new LocationClientOption();
			option.setOpenGps(true);
			option.setAddrType("all");// 返回的定位结果包含地址信息
			option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
			option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
			mLocationClient.setLocOption(option); 
		}

	public void switchDownload() {
		btn_left.setBackgroundResource(R.drawable.left_pressed);
		btn_right.setBackgroundResource(R.drawable.right_normal);
		layout_download.setVisibility(View.VISIBLE);
		scroll_citylist.setVisibility(View.GONE);
	}

	public void switchCityList() {
		btn_left.setBackgroundResource(R.drawable.left_normal);
		btn_right.setBackgroundResource(R.drawable.right_pressed);
		layout_download.setVisibility(View.GONE);
		scroll_citylist.setVisibility(View.VISIBLE);
		scroll_citylist.smoothScrollTo(0, 0);
	}

	/**
	 * 更新状态显示
	 */
	public void updateView() {
		records0 = mOffline.getAllUpdateInfo();
		if (records0 == null) {
			records0 = new ArrayList<MKOLUpdateElement>();
		}
		//初始化大小,与值		
				for(int i=length;i<records0.size();i++){
					IsClick[i]=true;
					Log.i("TAGsecond",i+"|"+ IsClick[i]+"");
				}
				length=records0.size();
		localadapter.notifyDataSetChanged();
	}

	@SuppressLint("DefaultLocale")
	public String formatDataSize(int size) {
		String ret = "";
		if (size < (1024 * 1024)) {
			ret = String.format("%dK", size / 1024);
		} else {
			ret = String.format("%.1fM", size / (1024 * 1024.0));
		}
		return ret;
	}

	@Override
	public void onGetOfflineMapState(int type, int state) {
		switch (type) {
		case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
			MKOLUpdateElement update = mOffline.getUpdateInfo(state);
			// 处理下载进度更新提示
			if (update != null) {
				//updateView();
				records0 = mOffline.getAllUpdateInfo();
				if (records0 == null) {
					records0 = new ArrayList<MKOLUpdateElement>();
				}				
				localadapter.notifyDataSetChanged();
			}
		}
			break;
		case MKOfflineMap.TYPE_NEW_OFFLINE:
			// 有新离线地图安装
			Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));
			break;
		case MKOfflineMap.TYPE_VER_UPDATE:
			// 版本更新提示
			// MKOLUpdateElement e = mOffline.getUpdateInfo(state);
			break;
		}

	}

	/**
	 * 离线地图管理列表适配器
	 */
	@SuppressLint("ViewHolder")
	public class LocalMapAdapter extends BaseAdapter implements
	View.OnClickListener {
		ViewHolder holder = null;
		@Override
		public int getCount() {
			return records0.size();
		}

		@Override
		public Object getItem(int index) {
			return records0.get(index);
		}

		@Override
		public long getItemId(int index) {
			return index;
		}

		@Override
		public View getView( final int index, View view, ViewGroup arg2) {
			//e = (MKOLUpdateElement) getItem(index);		
			if (view == null)
			{
			holder = new ViewHolder();
			view=LayoutInflater.from(OfflineActivity.this).inflate(R.layout.offline_local_item,null);  
			holder.text_name = (TextView) view.findViewById(R.id.text_name);			
			holder.text_status = (TextView) view.findViewById(R.id.text_status);
			holder.progressbar = (ProgressBar) view.findViewById(R.id.progressbar);
			holder.btn_display = (Button) view.findViewById(R.id.btn_display);
			holder.btn_start = (Button) view.findViewById(R.id.btn_start);
			holder.btn_remove = (Button) view.findViewById(R.id.btn_remove);	
			
			view.setTag(holder);
			}else{
				holder = (ViewHolder) view.getTag();
			}
			e = (MKOLUpdateElement) getItem(index);				
			holder.btn_start.setTag(index+"");  
			holder.btn_start.setOnClickListener(this);
			holder.btn_remove.setTag(index+"");  
			holder.btn_remove.setOnClickListener(this);
			holder.btn_display.setTag(index+"");  
			holder.btn_display.setOnClickListener(this);
			holder.text_name.setText(e.cityName + "  " + formatDataSize(e.serversize));
			holder.progressbar.setProgress(e.ratio);
			if (e.ratio != 100) {
				if (IsClick[index]) {
					holder.text_status.setText("正在下载" + e.ratio + "%");
					holder.text_status.setTextColor(Color.parseColor("#0093ee"));
					holder.btn_start.setText("暂停下载");
					
				} else {
					holder.text_status.setText("已暂停" + e.ratio + "%");
					holder.text_status.setTextColor(Color.parseColor("#f10a0a"));
					holder.btn_start.setText("开始下载");
				}
				holder.btn_display.setEnabled(false);
				holder.btn_start.setEnabled(true);
			} else {
				holder.text_status.setText("已下载");
				holder.text_status.setTextColor(Color.parseColor("#464646"));
				holder.btn_display.setEnabled(true);
				if (e.update) {
					holder.btn_start.setEnabled(true);
				} else {
					holder.btn_start.setEnabled(false);
				}
				holder.btn_start.setText("下载更新");
			}
			
			return view;
		}
		/**
		 * 方法名：onClick(View view)
		 * 功能：处理点击事件
		 * 参数：View view 被点击的view
		 * 返回值：无 */
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_start: {		
				int index1=Integer.parseInt((String)view.getTag());				
				final MKOLUpdateElement ee = (MKOLUpdateElement) getItem(index1);					
				if (ee.ratio != 100) {						
					if (IsClick[index1]) {
						holder.btn_start.setText("开始下载  ");
						mOffline.pause(ee.cityID);							
						holder.text_status.setText("已暂停" + ee.ratio + "%");
						holder.text_status.setTextColor(Color.parseColor("#f10a0a"));
					} else {
						holder.btn_start.setText("暂停下载");
						mOffline.start(ee.cityID);
						holder.text_status.setText("正在下载" + ee.ratio + "%");
						holder.text_status.setTextColor(Color.parseColor("#0093ee"));
					}						
					IsClick[index1]=!IsClick[index1];
					notifyDataSetChanged();
				}
				break;
			}
			case R.id.btn_remove:
				int index2=Integer.parseInt((String)view.getTag());				
				final MKOLUpdateElement ee1 = (MKOLUpdateElement) getItem(index2);	
				final ShowConfirmDlgA dialog = new ShowConfirmDlgA(
						OfflineActivity.this, "确定要删除地图离线包吗？","删除提示");
				TextView cancel = dialog.getCancel();
				TextView ok = dialog.getOk();
				ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						mOffline.remove(ee1.cityID);
						updateView();
						dialog.dismiss();
					}
				});
				cancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						dialog.dismiss();
					}
				});
				dialog.show();
				break;
			case R.id.btn_display:
				int index=Integer.parseInt((String)view.getTag());				
				final MKOLUpdateElement ee2 = (MKOLUpdateElement) getItem(index);	
				Intent intent = new Intent();
				intent.putExtra("x", ee2.geoPt.longitude);
				intent.putExtra("y", ee2.geoPt.latitude);
				intent.setClass(OfflineActivity.this, BaseMapActivity.class);
				startActivity(intent);
				break;
			}
		}

		private class ViewHolder
		{
			TextView text_name;
			TextView text_status;
			ProgressBar progressbar;
			Button btn_remove,btn_start,btn_display;
		}
	}

	@Override
	protected void onPause() {
//		try {
//			MKOLUpdateElement temp = mOffline.getUpdateInfo(e.cityID);
//			SharedPreferences.Editor spe = getSharedPreferences("data", 0).edit();
//			if (temp != null && temp.status == MKOLUpdateElement.DOWNLOADING) {
//				mOffline.pause(e.cityID);
//				spe.putInt("cityID", e.cityID);
//			} else {
//				spe.putInt("cityID", 0);
//			}
//			for(int i=0;i<IsClick.length;i++){
//				spe.putBoolean("IsClick["+i+"]", IsClick[i]);
//			}
//			//spe.putBoolean("click", click);
//			spe.commit();
//		} catch (Exception e) {
//		}
		
		super.onPause();
	}

	@Override
	protected void onResume() {
//		SharedPreferences sharedata = getSharedPreferences("data", 0);
//		int cityID = sharedata.getInt("cityID", 0);
//		if (cityID != 0) {
//			mOffline.start(cityID);
//		}
//		for(int i=0;i<IsClick.length;i++){
//			IsClick[i]=sharedata.getBoolean("IsClick["+i+"]", true);
//		}
		//click = sharedata.getBoolean("click", true);
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		/**
		 * 退出时，销毁离线地图模块
		 */
		mOffline.destroy();
		super.onDestroy();
	}
	
}
